# @Time    : 2025/01/27
# @Author  : 斯奎匝德(张仪伟)
# @File    : app.py
# @Software: PyCharm
#
#   高考加油！
#
import datetime
import json

from flask import Flask, render_template, send_from_directory, request, flash, jsonify

import Config
import Utils
from DatabaseHelper import Count,SearchArchiveByID,SearchArchiveByKeyword,UpdateArchive,DeleteDataById
from FileProcessor import FileProcessor
from SubmitProcessor import SubmitProcessor

app = Flask(__name__)
app.config["FILES"] = "templates"

app.register_blueprint(FileProcessor, url_prefix="/")
app.register_blueprint(SubmitProcessor, url_prefix="/")

#   该方法即将被抛弃，我们将使用安全的文件接口
# @app.route("/<path:filename>", strict_slashes=False)
# def templates(filename):
#       return send_from_directory(app.config["FILES"], filename)


@app.route("/publish",strict_slashes=False,methods=["GET"])
def publishTest():
    return render_template("publishMdui.html"),200

@app.route("/detailDataPage",strict_slashes=False,methods=["GET"])
def detailDataPage():
    return render_template("detailDataPage.html"),200

@app.route('/update',strict_slashes=False,methods=["POST"])
def update():
    JSONData = json.loads(request.data.decode())
    try:
        UpdateArchive(int(JSONData["id"]),
                  JSONData["title"],
                  JSONData["content"],
                  JSONData["tags"],
                  JSONData["category"],
                  Utils.GetTimeNow(True))
    except Exception as e:
        return '{"error_code":1,"message":"%s"}' % e
    return '{"error_code":0,"message":"success"}'

@app.route("/edit",strict_slashes=False,methods=["GET","POST"])
def editPage():
    return render_template("edit.html")

@app.route("/delete",strict_slashes=False,methods=["GET","POST"])
def deletePage():
    try:
        id = int(request.values.get("id"))
    except Exception as e:
        return jsonify({'error_code': 1, 'message': e}), 200
    result = DeleteDataById(id)
    if result[0] == False:
        return jsonify({'error_code': 1, 'message': result}),200
    else:
        return jsonify({'error_code': 0, 'message': 'success'}),200


@app.route("/searchEngine",strict_slashes=False,methods=["GET","POST"])
def searchEngine():
    keyword = request.values.get("keyword")
    try:
        keyword = keyword
    except ValueError:
        return jsonify({'error_code': 1, 'message': '参数错误'}),400
    result = SearchArchiveByKeyword(keyword)
    if result[0] == False:
        return jsonify({'error_code': 1, 'message': result}),200
    else:
        return jsonify({'error_code': 0, 'message': 'Found', 'result':result}),200
    """
    数据对照：
        result[0] (id)
        result[1] (uuid)
        result[2] (title)
        result[3] (content)
        result[4] (comments)
        result[5] (category)
        result[6] (tags)
        result[7] (unixTime/10位)
    """

@app.route("/detailData",strict_slashes=False,methods=["GET","POST"])
def detailData():
    id = request.values.get("id")
    try:
        id = int(id)
    except ValueError:
        return jsonify({'error_code': 1, 'message': '参数错误'}), 400
    result = SearchArchiveByID(id)
    if result[0] == False:
        return jsonify({'error_code': 1, 'message': result[1]}), 200
    else:
        time = datetime.datetime.fromtimestamp(result[7]).strftime("%Y-%m-%d %H:%M:%S")
        if result[5] == "":
            category = ""
        else:
            category = Config.categories[result[5]]
        return jsonify({'error_code':0,
                        'id': result[0],
                        'uuid': result[1],
                        'title': result[2],
                        'content': result[3],
                        'comments': result[4],
                        'category': category,
                        'tags': result[6],
                        'unixTime': time}), 200

@app.route("/",strict_slashes=False,methods=["GET"])
def index():
    total_content = Count()
    return render_template("searchTip.html", total_content=total_content)
if __name__ == "__main__":
    app.run(port=80, host="0.0.0.0", debug=True)
